package com.ssw.config;

import io.netty.util.internal.logging.Log4J2LoggerFactory;
import lombok.extern.log4j.Log4j2;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

/**
 * @Author: 孙常胜
 * @CreateTime: 2021/7/23 15:45
 * @Description:
 */
@Component
public class MessageProducer {
    @Value("${rocketMq.address}")
    private String rocketMqAddress;
    @Value("${rocketMq.group}")
    private String producerGroup;

    private DefaultMQProducer producer;

    //对象在用之前必须要调用一次，只能初始化一次
    public void start() {
        try {
            producer = new DefaultMQProducer(producerGroup);
            producer.setNamesrvAddr(rocketMqAddress);
            this.producer.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 异步发送mq
     * @param topic
     * @param tags
     * @param body
     */
    @Async
    public void sendMessage(String topic, String tags, String body) {
        try {
            Message message = new Message(topic, tags, body.getBytes("UTF-8"));
            producer.send(message, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    System.out.println("消息生产成功, sendResult:{}" + sendResult);
                }

                @Override
                public void onException(Throwable throwable) {
                    Integer retryTimes = producer.getRetryTimesWhenSendAsyncFailed();
                    System.out.println("消息生产失败, retryTimes:{}" + retryTimes);
                }
            });
        } catch (Exception e) {
            System.out.println("消息生产失败，topic:{}, tags:{}, body:{}" + topic + "-----" + tags + "-----" + body);
        }
    }
}
